var chatListener = null;
var memberListListener = null;
var messageListener = null;
var messageLimit = 15;

// Detect whether device supports orientationchange event, otherwise fall back to the resize event.
var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() { updateChatUI();}, false);
        
/*
 * loadChat: function to handle loading of a chat
 */
function loadChat(chatid){
        var lastmsgid = document.getElementById("lastmsgid").value;

        // Set up the request
        var payload = "chatid=" + encodeURI(chatid) + "&lastmsgid=" + encodeURI(lastmsgid);
        payload += "&doAction=";
        
        // If this is the initial signon (i.e., no comments in the chat contents
        // box), send a 'loadChat' request; otherwise, check for new messages.
        if(document.getElementById("chat_contents").childNodes.length==0) {
            payload += "loadChat";
        } else {
            payload += "getNewMessages";
        }

	x$('#chat_contents').xhr('_eventManager.jsp', {
            data: payload,
            callback:function(){ loadChatData(this.responseText) }
        });
}
 
// callback function to handle return from chatloader servlet
function loadChatData(data) {
    var cc = document.getElementById("chat_contents");
    var chatid = document.getElementById("chatid").value;
    var userid = document.getElementById("userid").value;

    if (data=="false") {
            signOff(userid);
            cc.innerHTML = "<p style='color: #990000'><b>The chat has been closed</b></p>";
    } else if (chatid > 0) {
            cc.innerHTML += data;
            cc.lastChild.scrollIntoView(true);
            cc.scrollTop = cc.scrollHeight;
 
            var lmsgid = document.getElementById("lastmsgid");
            if (cc.childNodes.length > 0 ) {
                lmsgid.value = cc.lastChild.getAttribute("id");
            }   
        
            // Drop old messages
            dropOldMessages(cc);  
    }
}   
        
// function to handle adding to a chat
function addComment(){
            document.getElementById("doAction").value = "addComment";
            var comment = document.getElementById("comment").value;
            if(comment=="") {
                comment = document.getElementById("comment").innerHTML;
            }

            if(comment != "") {
                // Set up the request
                var payload = "doAction=" + encodeURI(document.getElementById("doAction").value);
                payload += "&userid=" + encodeURI(document.getElementById("userid").value);
                payload += "&chatid=" + encodeURI(document.getElementById("chatid").value);
                payload += "&lastmsgid=" + encodeURI(document.getElementById("lastmsgid").value);
                payload += "&comment=" + encodeURI(comment);

                // Update the user's status on the server and the GUI  
                x$('#chat_contents').xhr('_eventManager.jsp', {
                    headers: [{name:"Content-Length", value: payload.length},
                        {name:"Content-type", value:"application/x-www-form-urlencoded"},
                        {name:"Connection", value: "close"}],
                    method: "post",
                    data: payload,
                    callback:function(){ loadChatData(this.responseText) }
                });
                document.getElementById("comment").value = "";
			window.scrollTo(0,0);
            } else {
                alert ("Please type a comment.");
            }
}
                       
// function to handle signoff
function signOff(){
	var userid = document.getElementById("userid").value;
	var chatid = document.getElementById("chatid").value;
	
	// Prepare to signoff; stop the chat listeners
	document.getElementById("doAction").value = "signoff";
        stopListeners();
      
        // Set up the request
	var payload = "doAction=" + encodeURI("signoff");
        payload += "&userid=" + encodeURI(userid);
        payload += "&chatid=" + encodeURI(chatid);

	// Update the user's status on the server and the GUI  
	x$('#chat_contents').xhr('_userManager.jsp', {
                headers: [{name:"Content-Length", value: payload.length},
                    {name:"Content-type", value:"application/x-www-form-urlencoded"},
                    {name:"Connection", value: "close"}],
                method: "post",
                data: payload,
                callback:function(){ exitChat() }
        });

        // Set the chat ID in the GUI to zero
	document.getElementById("chatid").value = 0;
}

// callback function from signoff; 'graceful' exit from the chat
function exitChat() {
            toggleWindow(document.getElementById("chatTab"));

            // Hide the comment form
            x$("#commentfrm").setStyle("display", "none");

            // Say good-bye
            var cc = document.getElementById("chat_contents");
            cc.innerHTML = "<p style=\"color: #009900;\"><b>Thank you for participating!</b></p>";
            cc.innerHTML += "<p>This window will close in a moment...</p>";
            setTimeout("window.close()", 3000);
}
           
// function to handle signon
function signOn(chatID, userID){
            document.getElementById("doAction").value = "signon";

            // Set the height of the chat contents block
            updateChatUI();

            // Set up the request
            var payload = "doAction=" + encodeURI("signon");
            payload += "&userid=" + encodeURI(userID);
            payload += "&chatid=" + encodeURI(chatID);
 
            // User sign in
            x$('#chat_contents').xhr('_userManager.jsp', {
                headers: [{name:"Content-Length", value: payload.length},
                    {name:"Content-type", value:"application/x-www-form-urlencoded"},
                    {name:"Connection", value: "close"}],
                method: "post",
                data: payload,
                callback: function(){ openWindow() }
            });

            // Load the chat members & contents
            updateMembers(chatID);
            loadChat(chatID);
}

function openWindow() {
            var chatid = document.getElementById('chatid').value;
            var userid = document.getElementById('userid').value;
 
            // If we have a legit chat, start polling
            if(chatid > 0) {
                startListeners();
            }
            
            // Set up the request to get the chat's owner
            var payload = "doAction=getOwner";
            payload += "&userid=" + encodeURI(userid);
            payload += "&chatid=" + encodeURI(chatid);
            
            x$('#commentfrm').xhr('_userManager.jsp', {
                data: payload,
                callback:function(){ getOwner(this.responseText) }
            });
}

function getOwner(data) {
    var owner = data;
    var userid = document.getElementById("userid").value;
    var endChatNode = document.getElementById("endchat");
 
    if(userid == owner) {
        endChatNode.style.display='';
    } else {
        endChatNode.style.display='none';
    }
}

// function to handle ending a chat
function endChat(){
    var userid = document.getElementById("userid").value;
    var chatid = document.getElementById("chatid").value;
    var payload = "userid=" + userid + "&chatid=" + chatid;

        // End the chat
            x$('#commentfrm').xhr('../servlet/chatManagers.endChat', {
                data: payload,
                callback:function(){ }
            });

    signOff(userid);
}


// functions to handle updating the list of participants in a chat
function updateMembers(chatid) {
            // Set up the request to get the chat's owner
            var payload = "doAction=getAllChatters";
            payload += "&chatid=" + encodeURI(chatid);
            
            x$('#members').xhr('_eventManager.jsp', {
                data: payload,
            });
}

function loadMemberList(data) {
    document.getElementById("members").innerHTML = data;
}

function dropOldMessages(ccNode) {
    while(ccNode.childNodes.length > messageLimit) {
        ccNode.removeChild(ccNode.firstChild);
    }
}

// function to toggle between members and send private msg windows
function toggleWindow(node) {
    node.className = "selectedTab";
    if (node == document.getElementById("chatTab")) {
        document.getElementById("membersTab").className = "hiddenTab";
        x$('#commentfrm').setStyle('display', '');
        x$('#chat_contents').setStyle('display', '');
        x$('#membersblock').setStyle('display', 'none');
    } else {
        document.getElementById("chatTab").className = "hiddenTab";
        x$('#commentfrm').setStyle('display', 'none');
        x$('#chat_contents').setStyle('display', 'none');
        x$('#membersblock').setStyle('display', 'block');
   }
}

// function to update the chat interface on an orientation change
function updateChatUI() {
    var boxHeight = 0;
    var cc = document.getElementById('chat_contents');

    if(window.orientation%180==0) {
        boxHeight = .57*screen.height;
    } else {
        boxHeight = .33*screen.height;
    }

    cc.style.height = boxHeight + 'px';
    if(cc.hasChildNodes()) {
        cc.lastChild.scrollIntoView(true);
    }
    cc.scrollTop = cc.scrollHeight;
}

// Listener functions
function runListeners() {
    loadChat(document.getElementById("chatid").value);
    updateMembers(document.getElementById("chatid").value);  
}

function startListeners() {
    chatListener = setInterval('runListeners()', 4000);
}

function stopListeners() {
    clearInterval(chatListener);
    chatListener = null;
}
